<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <el-alert
        show-icon
        title="注意：只允许第三级分类设置相关参数！"
        type="warning"
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedCatetKeys"
            :options="catelist"
            :props="{ expandTrigger: 'hover', ...cateProps }"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            :disabled="isBtnDisabled"
            type="primary"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  @close="handelClose(i, scope.row)"
                  :key="i"
                  closable
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  @click="showInput(scope.row)"
                  class="button-new-tag"
                  size="small"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="showEditDialog(scope.row.attr_id)"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  >编辑</el-button
                >

                <el-button
                  @click="removeParams(scope.row.attr_id)"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only"
          ><el-button
            @click="addDialogVisible = true"
            :disabled="isBtnDisabled"
            type="primary"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  @close="handelClose(i, scope.row)"
                  :key="i"
                  closable
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  @click="showInput(scope.row)"
                  class="button-new-tag"
                  size="small"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="showEditDialog(scope.row.attr_id)"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button
                  @click="removeParams(scope.row.attr_id)"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table></el-tab-pane
        >
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      catelist: [],
      //指定级联选择器的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        // 可以单独选择一级分类，功能等同 change-on-select
        checkStrictly: true,
      },
      // 级联选择框双向绑定的数组
      selectedCatetKeys: [],
      // 被激活的页签
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态参数
      onlyTableData: [],
      // 添加对话框
      addDialogVisible: false,
      // 添加表单数据
      addForm: {
        attr_name: '',
      },
      // 添加表单的验证规则对象
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur',
          },
        ],
      },
      // 编辑对话框
      editDialogVisible: false,
      // 编辑表单数据
      editForm: {
        attr_name: '',
      },
      // 修改表单的验证规则对象
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur',
          },
        ],
      },
      // 文本输入框显示与隐藏
      inputVisible: false,
      // 文本输入框的值
      inputValue: '',
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类失败')
      res.data.forEach((i) => {
        // console.log(i)
        if (i.cat_level === 0) {
          i.disabled = true
        }
        if (Array.isArray(i.children)) {
          i.children.forEach((item) => {
            if (item.cat_level === 1) {
              item.disabled = true
            }
          })
        }
        // 如果有children就不能用，否则能用
        // i.disabled = true
        // if (i.children === undefined) {
        //   i.disabled = false
        // }
        // if (Array.isArray(i.children)) {
        //   i.children.forEach((item) => {
        //     item.disabled = true
        //     if (item.children === undefined) {
        //       item.disabled = false
        //     }
        //   })
        // }
        // i.disabled = Array.isArray(i.children) ? true : false
        // if (Array.isArray(i.children)) {
        //   i.children.forEach((item) => {
        //     item.disabled = Array.isArray(item.children) ? true : false
        //   })
        // }
      })
      this.catelist = res.data

      console.log(res)
    },
    // 级联选择框选中时触发
    handleChange() {
      this.getParamsData()
    },
    // tab页签点击事件
    handleTabClick() {
      this.getParamsData()
    },
    // 获取参数列表数据
    async getParamsData() {
      // console.log(this.selectedCatetKeys);
      if (this.selectedCatetKeys.length !== 3) {
        this.selectedCatetKeys = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      // 把res.data目录下的数组中的attr_vals字符串转化成字符串数组
      res.data.forEach((item) => {
        // 字符串attr_vals中通过空格分隔
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []

        // 为每个item添加一个bool类型inputVisible，显示或隐藏文本框
        item.inputVisible = false
        // 文本框的值
        item.inputValue = ''
      })
      // console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 监听添加对话框的关闭事件
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加按钮确认
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }

        this.$message.success('添加参数成功')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 编辑按钮对话框
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }

      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听编辑对话框的关闭事件
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    //点击按钮修改参数
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('编辑参数失败')
        }

        this.$message.success('编辑参数成功')
        this.editDialogVisible = false
        this.getParamsData()
      })
    },
    // 删除参数
    async removeParams(id) {
      const confirm = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      console.log(confirm)

      if (confirm !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      // 重新请求参数列表
      this.getParamsData()
    },
    // 点击新添加Tag按钮
    showInput(row) {
      row.inputVisible = true
      // $nextTick方法作用：当页面元素被重新渲染后，才会指定回调函数中的代码
      // 当inputVisible被重置为true后，需要重新渲染页面元素，所以需要在这个函数中获取文本对象，否则无效
      this.$nextTick((_) => {
        // 获取文本框dom对象，获取焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除对应参数
    handelClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    // 文本框按下enter键或失去焦点
    handleInputConfirm(row) {
      // 判断输入内容是否有效，即去除空格
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果没有return， 将输入的内容添加到attr_vals中
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起网络请求保存修改到数据库
      this.saveAttrVals(row)
    },
    // 保存attr_vals中的改变，保存到数据库中
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )

      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getParamsData()
    },
  },
  computed: {
    // 如果按钮需要被禁用，则返回true
    isBtnDisabled() {
      if (this.selectedCatetKeys.length !== 3) {
        return true
      }
      return false
    },
    // todo 对象互转url参数
    // 当前选中的3级分类id
    cateId() {
      if (this.selectedCatetKeys.length === 3) {
        return this.selectedCatetKeys[2]
      }
      return null
    },
    // 根据计算标题的文本
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态参数'
    },
  },
}
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin-left: 15px;
}
.input-new-tag {
  width: 100px;
  margin-left: 15px;
}
.button-new-tag {
  width: 100px;
  margin-left: 15px;
}
</style>
